package com.example.demo.utils;


import com.example.demo.config.CommonConfig;
import com.lowagie.text.pdf.BaseFont;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;

public class FlySaucerUtil {
    private static Logger logger = LoggerFactory.getLogger(FlySaucerUtil.class);

    private static ITextRenderer renderer=new ITextRenderer();
//    public static String pdfFileDir="E:\\pdf\\";
//    public static String imgFileDir="D:/program/nginx-1.12.0/html/image/";
//    private static String fontFamilySupport="arialunicodems.ttf";
    /**
     *
     * @param buf 需要转换的String
     * @param pdfFileName
     * @throws Exception
     */
    public static void createPdf(StringBuffer buf,String pdfFileName) throws Exception{
        logger.debug("当前使用的xhtml信息：buf:{}",buf);
        //解决renderer对中文的支持问题
        setCharSupport(CommonConfig.getVal_font_family_support());
        //解决图片的相对路径问题
        renderer.getSharedContext().setBaseURL(CommonConfig.getVal_resourse_path());
       logger.info("temp:{}",renderer.getSharedContext().getBaseURL());
        //将需转换的内容以UTF-8的方式转换成字节数组
        byte[] bytes=buf.toString().getBytes("UTF-8");
        //根据字节数组创建字节数组输入流
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        //开始将流转换成文档对象
        InputSource is = new InputSource(bais);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(is);
        //将需转换的xhtml文档与转换器关联
        renderer.setDocument(doc, null);
        renderer.layout();
        //准备pdf文件输出流
        String filename = CommonConfig.getVal_resourse_path()+pdfFileName+".pdf";
        BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream(filename));
        //根据pdf文件输出流创建pdf
        renderer.createPDF(bufferedOutput);
        bufferedOutput.flush();
        bufferedOutput.close();
    }

    /**
     *
     * @param fileInput 需要转换的html，xml文件
     * @param pdfFileName 生成的pdf名称
     * @throws Exception
     */
    public static void createPdf(InputStream fileInput,String pdfFileName) throws Exception{
        StringBuffer strBuf=new StringBuffer();
//开始将文件流转换成StringBuffer
        BufferedReader bufReader=new BufferedReader(new InputStreamReader(fileInput,"UTF-8"));
        String buf = bufReader.readLine();
        while(buf!=null){
          //  buf = new String(buf.getBytes("UTF-8"),"utf-8");
            strBuf.append(buf);
            buf = bufReader.readLine();
        }

        logger.info("从文件流里面读出的xhtml信息：{}",strBuf);
//开始创建pdf
        createPdf(strBuf,pdfFileName);
    }



    /**
     *
     * @param support 字符设置，若是要显示中文，
     * 则参数须为：C:/Windows/Fonts/arialuni.ttf
     * @return 返回该字符设置的字体fontFamilyName
     * @throws Exception
     */
    private static String[] setCharSupport(String support) throws Exception{
        renderer.getFontResolver().addFont(support,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
//        BaseFont bfChinese= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
     //   renderer.getFontResolver().addFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
      /*  BaseFont font = BaseFont.createFont(support, BaseFont.IDENTITY_H , BaseFont.NOT_EMBEDDED);
        String[] fontFamilyName = TrueTypeUtil.getFamilyNames(font);
       // String fontFamilyName = "";
        System.out.println("fontFamilyName:"+fontFamilyName);
        return fontFamilyName;*/
       return null;
    }

}
